package com.weir.resources.permissions.controller.feign;

import com.weir.resources.permissions.entity.PermMenu;
import com.weir.resources.permissions.mapper.PermMenuMapper;
import com.weir.resources.permissions.mapper.PermRoleMapper;
import com.weir.resources.permissions.mapper.PermUserMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.weir.permissions.api.IUserFeignService;
import com.weir.permissions.vo.UserInfo;
import com.weir.resources.permissions.entity.PermUser;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Api(tags = { "用户Feign管理" })
@RestController
public class UserFeignServiceImpl implements IUserFeignService {
	private static final Logger LOGGER = LoggerFactory.getLogger(UserFeignServiceImpl.class);
	@Autowired
	private PermUserMapper permUserMapper;
	@Autowired
	private PermMenuMapper permMenuMapper;
	@Autowired
	private PermRoleMapper permRoleMapper;

	@ApiOperation("获取用户角色权限")
	@GetMapping("/getUser/{username}/")
	@Override
	public UserInfo getUser(@PathVariable("username") String username) {
		PermUser permUser = permUserMapper.selectOne(new QueryWrapper<PermUser>().eq("username", username.trim()));
		if (permUser == null) {
			return null;
		}

		Set<String> grantedAuthorities = new HashSet<>();

		List<String> roleCodes = permRoleMapper.selectCodeByUserId(permUser.getId());
		if (!CollectionUtils.isEmpty(roleCodes)){
			for (String roleCode : roleCodes) {
				//角色必须是ROLE_开头
				grantedAuthorities.add("ROLE_" + roleCode);
			}
		}

		List<PermMenu> permMenus = permMenuMapper.selectByUserId(permUser.getId());
		for (PermMenu permMenu : permMenus) {
			//获取权限
			grantedAuthorities.add(permMenu.getCode());
		}
		UserInfo user = new UserInfo(permUser.getUsername(), permUser.getPwd(), grantedAuthorities);
		LOGGER.info("UserFeignServiceImpl----" + user);
		return user;
	}
}
